package com.daisuxia.web.synchronization;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.constant.Constant;
import com.daisuxia.web.util.JedisDataClient;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;

import java.util.*;

@Service
public class RedisUtil {

	private static Logger logger = Logger.getLogger(RedisUtil.class);

	@Autowired
	JedisCluster jedisCluster;
	/**
	 * 删除redis中的key
	 */
	public void delRedisKey(String key){
		try{
			jedisCluster.del(key);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	/**
	 * 获取所有的redis数据
	 */
	public Set<String> keys(String pattern){
		logger.info("RedisUtil Start getting keys...");
		Set<String> keys = new HashSet<String>();
		Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
		for(String k : clusterNodes.keySet()){
			logger.info("RedisUtil Getting keys from = "+ k);
			JedisPool jp = clusterNodes.get(k);
			Jedis connection = jp.getResource();
			try {
				keys.addAll(connection.keys(pattern));
			} catch(Exception e){
				logger.error("RedisUtil Getting keys error: {}", e);
			} finally{
				logger.debug("RedisUtil Connection closed.");
				connection.close();
			}
		}
		logger.info("RedisUtil cluster Keys gotten!");
		return keys;
	}
	//获取后台推送的订单
	public List<String> getAllCSKeys() {
		List<String> allList = new ArrayList<String>();
		List<String> OVERDUE_ = getAllKeys(Constant.TYPE_OVERDUE_+"*");
		List<String> RENEWAL_ = getAllKeys(Constant.TYPE_RENEWAL_+"*");
		List<String> TYPE_REPAY_ = getAllKeys(Constant.TYPE_REPAY_+"*");
		List<String> TYPE_WITHHOLD_ = getAllKeys(Constant.TYPE_WITHHOLD_+"*");
		if(OVERDUE_!=null&&OVERDUE_.size()>0)
		allList.addAll(OVERDUE_);
		if(RENEWAL_!=null&&RENEWAL_.size()>0)
		allList.addAll(RENEWAL_);
		if(TYPE_REPAY_!=null&&TYPE_REPAY_.size()>0)
		allList.addAll(TYPE_REPAY_);
		if(TYPE_WITHHOLD_!=null&&TYPE_WITHHOLD_.size()>0)
		allList.addAll(TYPE_WITHHOLD_);
		return allList;
	}

	public List<String> getAllKeys(String pattern) {
		List<String> keyList = new ArrayList<String>();
		try {
			Set<String> keys = keys(pattern);
			Iterator<String> it = keys.iterator();
			while (it.hasNext()) {
				String key = it.next();
				logger.info("RedisUtil key = "+key);
				keyList.add(key);
			}
			return keyList;
		} catch (Exception e){
			logger.error("RedisUtil getAllkeys error {}",e);
			return null;
		}
	}

	public boolean exists(String key){
		return jedisCluster.exists(key);
	}

}
